package com.express.service;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.express.basic.constant.ExpressConstant;
import com.express.dao.mapper.AppVersionMapperExt;
import com.express.dao.pojo.AppVersion;
import com.express.dao.pojo.AppVersionExample;
import com.express.param.ClientVersion;
import com.express.param.FindAppVersionReq;

@Service
public class AppVersionCodeService extends BaseService<AppVersion, AppVersionExample>{

	@Autowired
	private AppVersionMapperExt appVersionMapperExt;
	
	public AppVersion findMaxVersionCode(FindAppVersionReq req){
		AppVersion appVersion = appVersionMapperExt.findMaxVersionCode(req.getOsType());

		return appVersion;
	}
	
	
	public ClientVersion findAppVersion(FindAppVersionReq req){
		ClientVersion clientVersion = new ClientVersion();
		
		AppVersion appVersion = findMaxVersionCode(req);
		Optional<AppVersion> possible = Optional.ofNullable(appVersion);
		if(!possible.isPresent())
			return clientVersion;		

		
		//小于最低要求的版本号
		if(req.getVersionCode() < possible.get().getLatestVersionCode()){
			buildVersion(clientVersion, possible.get());
			clientVersion.setType(ExpressConstant.VERSION_MUST);//强制更新
			return clientVersion;
		}else if(req.getVersionCode() >= possible.get().getLatestVersionCode() 
				&& req.getVersionCode() < possible.get().getVersionCode()){
			buildVersion(clientVersion, possible.get());
			clientVersion.setType(ExpressConstant.VERSION_ASK);//询问是否更新
		}else{
			buildVersion(clientVersion, possible.get());
			clientVersion.setType(ExpressConstant.VERSION_NOT);
		}
		return clientVersion;	
		
	}
	
	private void buildVersion(ClientVersion clientVersion,AppVersion appVersion){
		clientVersion.setDownUrl(appVersion.getDownUrl());
		clientVersion.setUpdateText(appVersion.getUpdateText());
		clientVersion.setVersionCode(appVersion.getVersionCode());
	}
	
}
